package cn.edu.xmist.thread;

import java.util.Map;
import java.util.concurrent.*;

/**
 * @author zhongjinbin 2021/4/17
 * @since 0.0.1
 */
public class BatchThreadPool {

    private static LinkedBlockingDeque<Request> queue = new LinkedBlockingDeque<>();

    static {
        ScheduledExecutorService scheduledExecutorService = new ScheduledThreadPoolExecutor(1);
        scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                int size = queue.size();
                if (size==0) {
                    return;
                }
            }
        }, 0, 10, TimeUnit.MILLISECONDS);
    }

    private static int MAX_THREADS = 1000;

    private static CountDownLatch cdt = new CountDownLatch(1);

    static class Request{
        String no;
        CompletableFuture<Map<String, Object>> wife;

        public String getNo() {
            return no;
        }

        public void setNo(String no) {
            this.no = no;
        }

        public CompletableFuture<Map<String, Object>> getWife() {
            return wife;
        }

        public void setWife(CompletableFuture<Map<String, Object>> wife) {
            this.wife = wife;
        }
    }

    public static void main(String[] args) {
        try {
            testInterface();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void testInterface() throws InterruptedException {
        for (int i = 0; i < MAX_THREADS; i++) {
            Thread t = new Thread(()->{
                try {
                    cdt.await();
                    // 模拟远程接口调用
                    Map<String, Object> result = queryForResult();
                } catch (InterruptedException | ExecutionException e) {
                    e.printStackTrace();
                }
            });
            t.start();
        }

        cdt.countDown();

        Thread.sleep(2000);
    }

    private static Map<String, Object> queryForResult() throws ExecutionException, InterruptedException {
        Thread thread = Thread.currentThread();
        System.out.println("接口被" + thread.getName() + "调用了");

        CompletableFuture<Map<String, Object>> wife = new CompletableFuture<>();

        Request request = new Request();
        request.setNo(thread.getName());
        request.setWife(wife);

        queue.add(request);
        return wife.get();
    }
}
